import config from '../../config.js'
import utils from '../../utils/utils.js'

let qcloud = require('../../utils/wafer2-client-sdk/index.js')
qcloud.setLoginUrl(config.baseUrl + '/weapp/login')

Page({
    data: {
        input: '',
        todos: [],
        leftCount: 0,
        allCompleted: false,
        logs: []
    },

    save: function () {
        wx.setStorageSync('todo_list', this.data.todos)
        wx.setStorageSync('todo_logs', this.data.logs)
    },

    init: function () {
        let todos = wx.getStorageSync('todo_list')
        if (todos) {
            let leftCount = todos.filter(function (item) {
                return !item.completed
            }).length
            this.setData({todos: todos, leftCount: leftCount})
        }
        let logs = wx.getStorageSync('todo_logs')
        if (logs) {
            this.setData({logs: logs})
        }
    },

    onShow: function () {
        this.init()
        // qcloud.request({
        //     url: config.baseUrl+'/weapp/todo',
        //     method: 'PUT',
        //     data: {
        //         todo: {
        //             name: '666',
        //             desc: '777',
        //             update_time: utils.formatDate(new Date()),
        //             create_time: new Date('2018-10-13 21:43:56'),
        //             completed: false,
        //             log: {
        //                 done: '111111',
        //                 not_done: '00000',
        //                 progress: 100,
        //                 time: utils.formatDate(new Date())
        //             }
        //         }
        //     },
        //     success: function (response) {
        //         console.log(response)
        //     },
        //     fail: function (err) {
        //         console.log(err)
        //     }
        // })
    },

    inputChangeHandle: function (e) {
        this.setData({input: e.detail.value})
    },

    addTodoHandle: function () {
        if (!this.data.input || !this.data.input.trim()) return
        let todos = this.data.todos
        let todo = {
            name: this.data.input,
            completed: false,
            update_time: utils.formatDate(new Date()),
            create_time: utils.formatDate(new Date())
        }
        todos.push(todo)
        let logs = this.data.logs
        logs.push({
            timestamp: utils.formatDate(new Date()),
            action: 'Add',
            name: this.data.input
        })
        qcloud.request({
            login: true,
            url: config.baseUrl + '/weapp/todo',
            method: 'POST',
            data: {
                todo: todo
            },
            success: function (response) {
                console.log(response)
            },
            fail: function (err) {
                console.log(err)
            }
        })
        this.setData({
            input: '',
            todos: todos,
            leftCount: this.data.leftCount + 1,
            logs: logs
        })
        this.save()
    },

    toggleTodoHandle: function (e) {
        let index = e.currentTarget.dataset.index
        let todos = this.data.todos
        todos[index].completed = !todos[index].completed
        let logs = this.data.logs
        logs.push({
            timestamp: utils.formatDate(new Date()),
            action: todos[index].completed ? 'Finish' : 'Restart',
            name: todos[index].name
        })
        this.setData({
            todos: todos,
            leftCount: this.data.leftCount + (todos[index].completed ? -1 : 1),
            logs: logs
        })
        this.save()
    },

    removeTodoHandle: function (e) {
        let index = e.currentTarget.dataset.index
        let todos = this.data.todos
        let remove = todos.splice(index, 1)[0]
        let logs = this.data.logs
        logs.push({timestamp: utils.formatDate(new Date()), action: 'Remove', name: remove.name})
        this.setData({
            todos: todos,
            leftCount: this.data.leftCount - (remove.completed ? 0 : 1),
            logs: logs
        })
        this.save()
    },

    toggleAllHandle: function (e) {
        this.data.allCompleted = !this.data.allCompleted
        let todos = this.data.todos
        for (let i = todos.length - 1; i >= 0; i--) {
            todos[i].completed = this.data.allCompleted
        }
        let logs = this.data.logs
        logs.push({
            timestamp: utils.formatDate(new Date()),
            action: this.data.allCompleted ? 'Finish' : 'Restart',
            name: 'All todos'
        })
        this.setData({
            todos: todos,
            leftCount: this.data.allCompleted ? 0 : todos.length,
            logs: logs
        })
        this.save()
    },

    clearCompletedHandle() {
        let todos = this.data.todos
        let remains = []
        for (let i = 0; i < todos.length; i++) {
            todos[i].completed || remains.push(todos[i])
        }
        let logs = this.data.logs
        logs.push({
            timestamp: utils.formatDate(new Date()),
            action: 'Clear',
            name: 'Completed todo'
        })
        this.setData({todos: remains, logs: logs})
        this.save()
    },

    goDetailHandle(e) {
        let index = e.currentTarget.dataset.index
        wx.navigateTo({
            url: '/pages/detail/detail?index=' + index
        })
    },

    doLogin: function () {
        const session = qcloud.Session.get()

        if (session) {
            // 第二次登录
            // 或者本地已经有登录态
            // 可使用本函数更新登录态
            qcloud.loginWithCode({
                success: res => {
                    this.setData({userInfo: res, logged: true})
                    // util.showSuccess('登录成功')
                },
                fail: err => {
                    console.error(err)
                    // util.showModel('登录错误', err.message)
                }
            })
        } else {
            // 首次登录
            qcloud.login({
                success: res => {
                    this.setData({userInfo: res, logged: true})
                    // util.showSuccess('登录成功')
                },
                fail: err => {
                    console.error(err)
                    // util.showModel('登录错误', err.message)
                }
            })
        }
    }
})

